<template>
  <div id="evaluate">
    <c-title :hide="false" text="评价"></c-title>
    <div class="shop-goods">
      <div class="goods flex">
        <div class="img flex"><img  :src="main_images" /></div>
        <div class="goods-title ">{{ good.name }} </div>
      </div>
      <!--评论-->
      <div class="comment">
        <h3>评论：</h3>
        <van-cell-group>
          <van-field v-model="comment" type="textarea" placeholder="请输入评论内容~" rows="2" />
        </van-cell-group>
        <div class="print">
          <h3>晒图：</h3>
          <div class="print-img flex">
            <template v-for="(val, index) in fileList4">
              <div class="photobox flex" :key="index" style="max-width: 5.625rem;">
                <img :src="val" style="max-width: 5.625rem;" />
                <span class="iconfont icon-guanbi" @click="removeImg_1(index)"></span>
              </div>
            </template>
            <div class="img-upload flex">
              <van-uploader :disabled="fileList4.length >= 5" :after-read="multipleMethod_1" multiple>
                <div class="upload flex-a-c flex-j-c">
                  <div class="crucifix"></div>
                </div>
              </van-uploader>
            </div>

          </div>
          <div class="print-rate flex-a-c flex-j-sb">
            <h4>评分：</h4>
            <van-rate v-model="level" :size="20" color="var(--themeBaseColor)" />
          </div>
        </div>
      </div>
      <div class="mh-90"></div>
      <div class="evaluate-box" :class="{ 'pc-box': fun.isPc() }">
            <div @click="toComment" class="evaluate-btn">提交评价</div>
        </div>
    </div>
  </div>
</template>
<script>
import cTitle from "components/title";
import { Toast } from "vant";
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
export default {
  data() {
    return {
      main_images:"",
      good: "",
      content: "",
      level: 5,
      comment: "", // 评论内容
      photosize: 1024 * 1024 * 2, // 图片大小限制,
      upNumMaxOther: "", // 图片数量
      uploadUrl: "",
      fileList3: [],
      fileList4: [],
    };
  },
  methods: {
    getGoodDetail() {
      // 获取订单商品信息，该id为订单商品的id(不是商品id !!!)
      $http
        .get("plugin.kaipin-laboratory.frontend.product-plaza.get-product-detail", { id: this.$route.params.id }, "")
        .then(response => {
          if (response.result === 1) {
            this.good = response.data;
            this.main_images = response.data.main_images[0]
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    toComment() {
      if (this.comment.length == 0) {
        this.$dialog
          .confirm({ message: "您还没有输入相关的评论内容" })
          .then(() => {
            this.submitData();
          })
          .catch(() => { });
      } else {
        this.submitData();
      }
    },
    onphotosize(e) {
      if (e && e.length) {
        for (let i = 0; i < e.length; i++) {
          if (e[i].file.size > this.photosize) {
            console.log("图片超出大小", e[i]);
            this.imgPreview(e[i].file, 2);
          } else {
            this.onRead_2(e[i].file, true);
          }
        }
      } else {
        console.log("图片超出大小", e);
        this.imgPreview(e.file, 2);
      }
    },
    imgPreview(file, callback) {
      let self = this;
      // 判断支不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片转成base64格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          img.onload = function () {
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制
            var maxWidth = 400,
              maxHeight = 400;
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过400x400的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }

            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            // canvas转为blob并上传
            canvas.toBlob(function (blob) {
              // 图片ajax上传
              if (callback === 1) {
                self.onRead(blob, true);
              } else {
                // self.onRead_1(blob, true)
                self.multipleMethod_1(blob, true);
              }
            }, file.type || "image/png");
          };
        };
      }
    },
    // 判断多图上传，循环onRead_1方法
    multipleMethod_1(e, flag) {
      if (e && e.length) {
        for (let i = 0; i < e.length; i++) {
          this.onRead_2(e[i], flag);
        }
      } else {
        this.onRead_2(e, flag);
      }
    },
    // vant 多其他图片上传
    onRead_2(e, flag) {
      if (flag !== true) {
        // if (e.file.size > this.photosize) {
        //   this.imgPreview(e.file, 3)
        //   return false
        // }
      }
      var That = this;
      let fd = new FormData();
      if (this.upNumMaxOther == 5 || this.upNumMaxOther >= 5) {
        this.$notify({
          background: "#fef0f0",
          message: "图片数量已达到上限",
          color: "#f56c6c"
        });
        return false;
      }
      if (flag === true) {
        fd.append("file", e);
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      fd.append("attach", "upload");

      // 添加加载提示
      Toast.loading({
        message: " ",
        forbidClick: true
      });
      axios
        .post(this.uploadUrl, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          var responseData = response.data;
          if (responseData.result == 1) {
            That.upNumMax++;
            That.fileList3.push(responseData.data.img);

            if (flag === true) {
              That.fileList4.push(URL.createObjectURL(e));
            } else {
              That.fileList4.push(URL.createObjectURL(e.file));
            }
            Toast.clear();
          } else {
            Toast(responseData.msg);
            Toast.clear();
          }
        })
        .catch(error => {
          console.log(error);
          Toast.clear();
        });
    },
    removeImg_1(delIndex) {
      this.fileList3.splice(delIndex, 1);
      this.fileList4.splice(delIndex, 1);
      this.upNumMaxOther = this.fileList3.length;
    },
    // 提交数据到服务器
    submitData() {
      var newArr2 = [];
      if (this.fileList3.length != 0) {
        for (var i = 0; i < this.fileList3.length; i++) {
          newArr2.push(this.fileList3[i]);
        }
      } else {
        newArr2 = [];
      }
      // newArr2 = JSON.stringify(newArr2);
      let json = {
        product_id: this.$route.params.id,
        content: this.comment,
        score: this.level,
        images: newArr2
      };

      $http.post("plugin.kaipin-laboratory.frontend.product-plaza.participate-comment", json).then(
        response => {
          if (response.result == 1) {
            this.$dialog.alert({ message: response.msg }).then(() => {
              this.$router.go(-1);
            });
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function (response) {
          // error callback
        }
      );
    },
  },
  activated() {
    this.comment = "";
    this.fileList4 = [];
    this.level = 5;
    this.fileList3 = [];
    this.uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
    this.getGoodDetail();
  },
  components: { cTitle }
};

</script>
<style scoped>

.evaluate-btn {
    background-color: var(--themeBaseColor);
    border-radius: 1.2813rem;
    font-size: 0.875rem;
    height: 2.5rem;
    line-height: 2.5rem;
    font-weight: bold;
    color: #FFFFFF;
}

.pc-box {
    width: 375px;
    left: 50% !important;
    transform: translateX(-50%);
}

.evaluate-box {
    padding: 0.25rem .4375rem;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    background-color: #fff;
}
.comment ::v-deep .van-field {
  background-color: #F5F5F5;
  padding: 0.75rem;
  border-radius: 0.25rem;
}

.print-img ::v-deep .van-uploader__wrapper {
  border-radius: 0.25rem;
}

::v-deep .van-field__control::-webkit-input-placeholder {
  color: #666;
}

.pcStyle .shop-goods .evaluate-btn {
  left: auto;
}
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" rel="stylesheet/scss" scoped>
.ell {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  /* 定义显示的行数 */
  overflow: hidden;
}

.mh-90 {
  height: 5.625rem;
  clear: both;
}

.goods-hide {
  visibility: hidden;
}

.shop-goods {
  margin: 0.5rem 0.75rem 0 0.75rem;

  .goods {
    border-radius: 0.5rem;
    background-color: #FFFFFF;
    padding: 0.75rem;
    align-items: center;

    .img {
      // flex: 3;
      background: rgba(0, 0, 0, 0);
      margin: 0 0.25rem 0 0;

      img {
        width: 4.375rem;
        height: 4.375rem;
        margin: 0;
        border-radius: 0.25rem;
      }
    }

    .goods-title {
      font-weight: 400;
      font-size: 0.8125rem;
      color: #00001C;
      text-align: left;
      margin-left: .5rem;
    }

  }

  .comment {
    margin: 0.5rem 0 0 0;
    background-color: #fff;
    border-radius: 0.5rem;
    padding: 0.75rem;

    h3 {
      font-size: 0.875rem;
      line-height: 1.25rem;
      color: #333333;
      padding: 0 0 0.75rem 0;
      font-weight: 400;
      text-align: left;
    }

    .print {
      h3 {
        padding: 1.25rem 0 0.75rem 0;
      }

      .print-img {
        flex-wrap: wrap;
      }

      .photobox {
        width: 5.625rem;
        flex-wrap: wrap;
        margin: 0 1rem 1rem 0;
        position: relative;

        img {
          margin: 0;
          border-radius: 0.25rem;
          height: 5.625rem;
        }

        .icon-guanbi {
          color: #fff;
          position: absolute;
          top: -0.025rem;
          right: -0.875rem;
          transform: translate(-50%, -50%);
          z-index: 5;
          width: 0.9375rem;
          height: 0.9375rem;
          font-size: 0.625rem;
          background-color: rgba(0,0,0,.5);
          border-radius: 50%;
        }
      }

      .img-upload {
        position: relative;
        margin: 0 0 1rem 0;

        .upload {
          width: 5.625rem;
          height: 5.625rem;
          border-radius: 0.25rem;
          background-color: #F5F5F5;
          position: relative;

          .crucifix {
            /* 十字架样式 */
            width: 1.375rem;
            height: 0.125rem;
            background: #b2b2b2;
            border-radius: 0.625rem;
            position: relative;

            &::after {
              content: "";
              width: 1.375rem;
              height: 0.125rem;
              background: #b2b2b2;
              border-radius: 0.625rem;
              position: absolute;
              transform: rotate(-90deg);
              left: 0;
            }
          }
        }
      }

      .print-rate {
        padding: 0.25rem 0 0 0;

        h4 {
          font-size: 0.875rem;
          line-height: 1.25rem;
          color: #333333;
          font-weight: 400;
        }
      }
    }
  }

  .score-box {
    margin: 0.5rem 0 0 0;
    background-color: #FFFFFF;
    border-radius: 0.5rem;
    padding: 0.75rem;

    .score-item {
      padding: 0 0 0.75rem 0;

      &:last-child {
        padding: 0;
      }

      h3 {
        font-size: 0.875rem;
        font-weight: 400;
        line-height: 1.25rem;
        color: #333333;
      }
    }

  }

}
</style>